<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2020/7/30
 * Time: 15:06
 */
namespace app\admin\controller;
use think\Db;
use think\Request;
use Qiniu\Auth;// 引入鉴权类
use Qiniu\Storage\UploadManager;// 引入上传类
use Qiniu\Processing\PersistentFop;
require_once('../extend/qiniu/autoload.php');
Class Course extends Base {
    public function index(){
        if (request()->isAjax()) {
            extract(input());
            $map =array();
            if(isset($keyword)&&$keyword!="")
            {
                $map['course_name|course_teacher_name'] = ['like',"%" . $keyword . "%"];
            }
            if(isset($status)&&$status!="")
            {
                $map['f_id'] = $status;
            }
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 50;
            $count = Db::name('course')->alias('a')
                ->join('up_course_type uct','uct.course_type_id = a.f_id','left')
                ->where($map)
                ->count();// 获取总条数
            $lists = Db::name('course')->alias('a')
                ->join('up_course_type uct','uct.course_type_id = a.f_id','left')
                ->page($NowPage, $limits)
                ->where($map)
                ->field('a.*,uct.course_type_name')
                ->order('a.course_time desc')
                ->select();
            foreach ($lists as $key=>&$vo){
                $num = Db::table('up_course_chapter')->where('course_id',$vo['course_id'])->count();
                $vo['num'] = $num?$num:0;
            }

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        if(session('?course_id')){
            session('course_id',null);
        }
        $info = Db::table('up_course_type')->select();
        $this->assign('info',$info);
        return $this->fetch();
    }
    /***
     * @return \think\response\Json
     * 删除
     */
    public function del(){
        $task_id = input('param.id');
        //查询课程是否大于0
        //统计这个
        $num = Db::table('up_course_chapter')->where('course_id',$task_id)->count();
        if($num>0){
            Db::table('up_course_chapter')->where('course_id',$task_id)->delete();
        }
        $res = Db::table('up_course')->where('course_id',$task_id)->delete();
        if($res){
            return json(['code'=>200,'msg'=>'删除成功']);
        }else{
            return json(['code'=>100,'msg'=>'删除失败']);
        }
    }
    /***
     * @return \think\response\Json
     * 上架
     */
    public function up(){
        $task_id = input('param.id');
        $res = Db::name('course')->where('course_id',$task_id)->setField('course_status',1);
        if($res){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>100,'msg'=>'操作失败']);
        }
    }
    /***
     * @return \think\response\Json
     * 下架
     */
    public function down(){
        $task_id = input('param.id');
        $res = Db::name('course')->where('course_id',$task_id)->setField('course_status',2);
        if($res){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>100,'msg'=>'操作失败']);
        }
    }

    public function add(){
        if(Request::instance()->isPost()){
            $course_name = input('param.course_name');
            $f_id = input('param.f_id');
            $course_img = input('param.course_img');
            $course_all_time = input('param.course_all_time');
            $course_price = input('param.course_price');
            $course_zixun_num = input('param.course_zixun_num');
            $course_brief = input('param.course_brief');
            $course_teacher_name = input('param.course_teacher_name');
            $course_teacher_img = input('param.course_teacher_img');
            $course_teacher_brief = input('param.course_teacher_brief');

            $data['course_name'] = $course_name;
            $data['f_id'] = $f_id;
            $data['course_img'] = $course_img;
            $data['course_all_time'] = $course_all_time;
            $data['course_price'] = $course_price;
            $data['course_zixun_num'] = $course_zixun_num;
            $data['course_brief'] = $course_brief;
            $data['course_teacher_name'] = $course_teacher_name;
            $data['course_teacher_img'] = $course_teacher_img;
            $data['course_teacher_brief'] = $course_teacher_brief;
            $data['course_time'] = date('Y-m-d H:i:s');
            $res = Db::table('up_course')->insert($data);
            if($res){
                return json(['code' => 200, 'msg' => '添加成功']);
            }else{
                return json(['code' => 100, 'msg' => '添加失败']);
            }
        }
        $info = Db::table('up_course_type')->select();
        $this->assign('info',$info);
        return $this->fetch();
    }

    public function update(){
        if(Request::instance()->isPost()){
            $id = input('param.id');
            $course_name = input('param.course_name');
            $f_id = input('param.f_id');
            $course_img = input('param.course_img');
            $course_all_time = input('param.course_all_time');
            $course_price = input('param.course_price');
            $course_zixun_num = input('param.course_zixun_num');
            $course_brief = input('param.course_brief');
            $course_teacher_name = input('param.course_teacher_name');
            $course_teacher_img = input('param.course_teacher_img');
            $course_teacher_brief = input('param.course_teacher_brief');

            $data['course_name'] = $course_name;
            $data['f_id'] = $f_id;
            $data['course_all_time'] = $course_all_time;
            $data['course_price'] = $course_price;
            $data['course_zixun_num'] = $course_zixun_num;
            $data['course_brief'] = $course_brief;
            $data['course_teacher_name'] = $course_teacher_name;
            $data['course_teacher_brief'] = $course_teacher_brief;
            if(!empty($course_img)){
                $data['course_img'] = $course_img;
            }
            if(!empty($course_teacher_img)){
                $data['course_teacher_img'] = $course_teacher_img;
            }
            $res = Db::table('up_course')->where('course_id',$id)->update($data);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        $id = input('param.course_id');
        $info = Db::table('up_course_type')->select();
        $resList = Db::table('up_course')->where('course_id',$id)->find();
        $this->assign('info',$info);
        $this->assign('id',$id);
        $this->assign('res',$resList);
        return $this->fetch();
    }
    public function detail(){
        $id = input('param.course_id');
        $info1 = Db::table('up_course')->where('course_id',$id)->find();
        $info = Db::table('up_course_type')->select();
        $this->assign('res',$info1);
        $this->assign('info',$info);
        return $this->fetch();
    }


    public function index1(){
        if (request()->isAjax()) {
            extract(input());
            $where['a.course_id'] = session('course_id');
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('course_chapter')->alias('a')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('course_chapter')->alias('a')
                ->page($NowPage, $limits)
                ->where($where)
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        if(!session('?course_id')){
            session('course_id',input('id'));
        }
        return $this->fetch();
    }

    public function del1(){
        $task_id = input('param.id');

        $res = Db::table('up_course_chapter')->where('chapter_id',$task_id)->delete();

        if($res){
            return json(['code'=>200,'msg'=>'删除成功']);
        }else{
            return json(['code'=>100,'msg'=>'删除失败']);
        }
    }
    public function add1(){
        if(Request::instance()->isPost()){
            $params = input('param.');
            if(empty($params['video'])){
                return json(['code' => 100, 'msg' => '请上传视频']);
            }
            //转码的文件url
            $url = "http://qiniu.xiaoyidida.com/" . $params['video'];//未转码之前的视频url，用于获取时长
            //时长
            $a = file_get_contents($url . '?avinfo');
            $b = json_decode($a,true);
            $time = explode('.', $b['streams'][0]['duration']);
            $fen = floor($time[0]/60);
            $miao = floor(($time[0]-$fen*60)%60);
            $this->zhuanma($params['video']);
            $data = [
                'chapter_name' => $params['chapter_name'],//标题
                'chapter_url' => "http://qiniu.xiaoyidida.com/" . 'xydd_' . $params['video'],//视频
                'course_id' => session('course_id'),//视频ID
                'chapter_time' => date('Y-m-d H:i:s'),//创建时间
                'catalogue_time' => $fen . ':' . $miao//视频时长
            ];
            $res = Db::table('up_course_chapter')->insert($data);
            if($res){
                return json(['code' => 200, 'msg' => '添加成功']);
            }else{
                return json(['code' => 100, 'msg' => '添加失败']);
            }
        }
        return $this->fetch();
    }
    public function update1(){
        if(Request::instance()->isPost()){
            $params = input('param.');
            if(empty($params['video'])){
                return json(['code' => 100, 'msg' => '请上传视频']);
            }
            $old_url = Db::table('up_course_chapter')->where('chapter_id', $params['id'])->value('chapter_url');
            //转码的文件url
            //有视频但是和原视频地址不同
            if($params['video'] != '' && $params['video'] != $old_url){
                $url = "http://qiniu.xiaoyidida.com/" . $params['video'];//未转码之前的视频url，用于获取时长
                //时长
                $a = file_get_contents($url . '?avinfo');
                $b = json_decode($a,true);
                $time = explode('.', $b['streams'][0]['duration']);
                $fen = floor($time[0]/60);
                $miao = floor(($time[0]-$fen*60)%60);
                $this->zhuanma($params['video']);
                $data['chapter_url'] = "http://qiniu.xiaoyidida.com/" . 'xydd_' . $params['video'];//视频地址
                $data['catalogue_time'] = $fen . ':' . $miao;//视频时长
            }
            $data = [
                'chapter_name' => $params['chapter_name'],//标题
            ];
            $res = Db::table('up_course_chapter')->where('chapter_id',$params['id'])->update($data);
            if($res){
                return json(['code' => 200, 'msg' => '编辑成功']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
        }
        $id = input('param.id');
        $res = Db::table('up_course_chapter')->where('chapter_id',$id)->find();
        $this->assign('id',$id);
        $this->assign('res',$res);
        return $this->fetch();
    }

    /**
     * 转码
     * @param $key
     */
    public function zhuanma($key){
        set_time_limit (0);
        $accessKey = config('qiniu')['accessKey'];
        $secretKey = config('qiniu')['secretKey'];
        $bucket = config('qiniu')['bucket'];
        $auth = new Auth($accessKey, $secretKey);
        $pipeline = 'xy-dd';//多媒体队列名
        $force = false;
        //转码完成后通知到你的业务服务器。
//        $notifyUrl = '= 'http://cjtdcms.xuanwumobile.com/super#advert_manage';

        $config = new \Qiniu\Config();
        $pfop = new PersistentFop($auth, $config);
        $fops = "avthumb/mp4/vcodec/libx264/|saveas/" . \Qiniu\base64_urlSafeEncode($bucket .  ":" . 'xydd_' . $key);
        list($id, $err) = $pfop->execute($bucket, $key, $fops, $pipeline, '', $force);
        if($err !== null) {
            $res = $err;
        } else {
            $res = $id;
        }
    }
}